from django import template
import common.function as myfc


register = template.Library()

@register.filter
def timestampToDatetime(v,f="%Y-%m-%d %H:%M:%S"):
  dt=int(v)
  if dt == 0:
    return ""
  else:
    return myfc.timestampToDatetime(v,f)
  
@register.filter
def stringToInt(str):
  return int(str)
  
@register.filter
def whetherornotToText(v):
  if v=="1":
    return "是"
  else:
    return "否"

@register.filter
def tofloat(v):
  '转为浮点数'
  t=0
  try:
    t=float(v)
  except ValueError:
    pass
  if t == 0:
    return ""
  else:
    return t

@register.filter
def toint(v):
  '转为整数'
  t=0
  try:
    t=int(float(v))
  except ValueError:
    pass
  if t == 0:
    return ""
  else:
    return t

@register.assignment_tag
def ckCheckboxChecked(v,s):
  '判断Checkbox是否选中'
  
  flat=","+str(v)+","
  if s.find(flat) > -1:
    return 'checked="checked"'
  else:
    return ""

@register.assignment_tag
def ckIsNotDisabled(v,s):
  '判断Checkbox是否选中'
  
  flat=","+str(v)+","
  if s.find(flat) > -1:
    return ""
  else:
    return 'disabled="disabled"'

@register.assignment_tag
def ckSelectSelected(v,s):
  '判断Select是否选中'
  
  if str(v) == str(s):
    return "selected"
  else:
    return ""

@register.filter
def returnBorrowDurationByRepaymentType(v,t):
  '显示限期值'
  
  if str(t) == "1":
    return int(v)
  else:
    return int(v)/30

@register.assignment_tag
def pagination(current_page,paginator,num_of_displaypages=10,num_of_backpages=4,arr_get=[]):
  '分页'
  
  num_of_frontpages = num_of_displaypages - num_of_backpages -3
  html=''
  
  more_param=""
  for key in arr_get:
    if key != "page":
      more_param+="&"+key+"="+arr_get[key]
  
  #  当总页数小于等于 显示页数 时，则将总页数全部显示
  if paginator.num_pages <= num_of_displaypages :
      for i in range(1,paginator.num_pages+1):
          html+= '<li ><a href="?page=%s%s">%s </a></li>'%(i,more_param,i)
      return html
  #  第一种情况 
  elif current_page.number <= num_of_displaypages-num_of_backpages:
      for i in range(1,num_of_displaypages+1):
          html+= '<li ><a href="?page=%s%s">%s </a></li>'%(i,more_param,i)
      return html
  #  第二种情况
  elif num_of_displaypages-num_of_frontpages <= current_page.number <= paginator.num_pages-num_of_backpages :
      html = '''
          <li><a href="?page=1">1</a></la>
          <li class="disabled"><a href="?page=1">...</a></la>

      '''
      for i in range(current_page.number-num_of_frontpages,current_page.number+num_of_backpages+1):
          html+='<li><a href="?page=%s%s">%s</a></la>'%(i,more_param,i)
      return html
  #  第三种情况
  else:
      html = '''
          <li><a href="?page=1">1</a></la>
          <li class="disabled"><a href="?page=1">...</a></la>

      '''
      for i in range(paginator.num_pages-num_of_backpages-num_of_frontpages,paginator.num_pages+1):
          html+='<li><a href="?page=%s%s">%s</a></la>'%(i,more_param,i)
      return html